package com.cci.kangdao.wechatOrder.util.wxsdk;

import com.cci.kangdao.azureAD.AzureService;
import com.cci.kangdao.azureAD.ManagementToken;
import com.cci.kangdao.utilTool.HttpUtils;
import com.cci.kangdao.utilTool.JsonUtils;
import com.cci.kangdao.utilTool.PropertiesUtil;
import com.cci.kangdao.wechatOrder.enums.wx.WxCgi;
import com.cci.kangdao.wechatOrder.enums.wx.WxSns;
import com.cci.kangdao.wechatOrder.model.wx.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *  微信工具类
 */
public class WxUtils {
    private static Logger log = Logger.getLogger(AzureService.class);

    /**
     * 获取访问token
     * @param appId
     * @param secret
     * @return
     */
    public static ManagementToken getToken(String appId,String secret){
        String url= WxCgi.ACCESS_TOKEN.convert(appId,secret);
        String body = HttpUtils.get(url, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return  EntityUtils.toString(httpEntity);
                }
                return EntityUtils.toString(response.getEntity());
            }
        },null);
        log.debug("getToken获取的返回数据="+body);
        if (StringUtils.isBlank(body)){
            log.error("获取token失败");
            return null;
        }
        ManagementToken token = JsonUtils.toJavaObject(body, ManagementToken.class);
        return token;
    }

    /**
     * 通过客户端的code获取openId
     * @param appId
     * @param secret
     * @param code
     * @return
     */
    public static ManagementToken getTokenByCode(String appId,String secret,String code){
        String url= WxSns.OAUTH2_ACCESS_TOKEN.convert(appId,secret,code);
        String body = HttpUtils.get(url, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return  EntityUtils.toString(httpEntity);
                }
                return EntityUtils.toString(response.getEntity());
            }
        },null);
        log.info("getTokenByCode获取的返回数据="+body);
        if (StringUtils.isBlank(body)){
            log.error("获取token失败");
            return null;
        }
        ManagementToken token = JsonUtils.toJavaObject(body, ManagementToken.class);
        return token;
    }

    /**
     * 刷新token
     * @param appId
     * @param accessToken
     * @return
     */
    public static ManagementToken getRefreshToken(String appId,String accessToken){
        String url= WxSns.OAUTH2_REFRESH_TOKEN.convert(appId,accessToken);
        String body = HttpUtils.get(url, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return  EntityUtils.toString(httpEntity);
                }
                return EntityUtils.toString(response.getEntity());
            }
        },null);
        log.debug("getRefreshToken获取的返回数据="+body);
        if (StringUtils.isBlank(body)){
            log.error("获取token失败");
            return null;
        }
        ManagementToken token = JsonUtils.toJavaObject(body, ManagementToken.class);
        return token;
    }


    /**
     *
     * @param pm
     * @param token
     * @return
     */
    public static WxResult wxPushMessage(PushMessage pm,String token){
        String url = WxCgi.MESSAGE.convert(token);
        String response = HttpUtils.postJson(url,JsonUtils.toJsonString(pm),new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return  EntityUtils.toString(httpEntity);
                }
                else{
                    return  EntityUtils.toString(response.getEntity());
                }
            }
        },null);
        log.debug("wxPushMessage获取的返回数据="+response);
        if (StringUtils.isBlank(response)){
            log.error("获取token失败");
            return null;
        }
        WxResult wxResult = JsonUtils.toJavaObject(response, WxResult.class);
        return wxResult;
    }

    /**
     *
     * @param openId
     * @param token
     * @return
     */
    public static WeChatUserInfo getUserInfo(String openId,String token){
        String url= WxCgi.USER_INFO.convert(token,openId);
        String body = HttpUtils.get(url, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return  EntityUtils.toString(httpEntity);
                }
                return EntityUtils.toString(response.getEntity());
            }
        },null);
        log.debug("getUserInfo获取的返回数据="+body);
        if (StringUtils.isBlank(body)){
            log.error("获取用户信息失败");
            return null;
        }
        WeChatUserInfo userInfo = JsonUtils.toJavaObject(body, WeChatUserInfo.class);
        return userInfo;
    }
    public static JsTicket getJsapiTicket(String accessToken) {
        String url = WxCgi.JSAPI_TICKET.convert(new String[]{accessToken});
        String body = (String)HttpUtils.get(url, new ResponseHandler<String>() {
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return EntityUtils.toString(httpEntity);
                } else {
                    return EntityUtils.toString(response.getEntity());
                }
            }
        }, (Header[])null);
        log.debug("getRefreshToken获取的返回数据=" + body);
        if (StringUtils.isBlank(body)) {
            log.error("获取token失败");
            return null;
        } else {
            JsTicket ticket = (JsTicket)JsonUtils.toJavaObject(body, JsTicket.class);
            return ticket;
        }
    }
    /**
     * 根据来源获取微信APPID
     * @param source
     * @return
     */
    public static WxAppInfo getWxAppInfo(Integer source){
        WxAppInfo info = null;
        String appid = "";
        String appsecret = "";
        switch (source){
            case 1:
                appid = PropertiesUtil.getProperties("projectconfig.properties", "dbuAppId");
                appsecret = PropertiesUtil.getProperties("projectconfig.properties", "dbuAppSecret");
                break;
            case 2:
                break;
            case 3:
                appid = PropertiesUtil.getProperties("projectconfig.properties", "dcecAppId");
                appsecret = PropertiesUtil.getProperties("projectconfig.properties", "dcecAppSecret");
                break;
            default:
                break;
        }
        if (StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(appsecret)){
            info = new WxAppInfo(appid,appsecret);
        }

        return info;
    }

    /**
     * 根据渠道获取消息模板
     * @param companyID
     * @param source
     * @return
     */
    public static String getWxTemplateId(Long companyID,Integer source){
        String templateId = null;
        switch (companyID.intValue()){
            case 1:
                templateId = PropertiesUtil.getProperties("projectconfig.properties", "dbuTemplateId");
                break;
            case 2:

                break;
            case 3:
                templateId = PropertiesUtil.getProperties("projectconfig.properties", "dcecTemplateId");
                break;
            default:
                break;
        }
        return templateId;
    }


    public static Map<String, String> getJsTicketSign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String signature = "";
        String string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException var8) {
            var8.printStackTrace();
        } catch (UnsupportedEncodingException var9) {
            var9.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
    }

    private static String byteToHex(byte[] hash) {
        Formatter formatter = new Formatter();
        byte[] var2 = hash;
        int var3 = hash.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            byte b = var2[var4];
            formatter.format("%02x", b);
        }

        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000L);
    }
}
